//
//  KDRootViewController.m
//  KongDays
//
//  Created by deeplu on 12. 12. 20..
//  Copyright (c) 2012년 BlueBeans. All rights reserved.
//

#import "KDDayListController.h"
#import "KDAppDelegate.h"
#import "KDNewDayController.h"
#import "KDDayTypeController.h"
#import "KDDayController.h"
#import "KDDayCardController.h"
#import "KDSettingsController.h"
#import "KDAboutController.h"
#import "KDTopDayTableViewCell.h"
#import "KDDayTableViewCell.h"
#import "NSDay.h"

@interface KDDayListController ()

- (void)showDayCard:(NSDay *)day;
- (void)initNavigationBar;
- (void)bindDayList;
- (void)addNewDay;

@end

@implementation KDDayListController
@synthesize dayArray;
@synthesize dayListTable;
@synthesize aboutButton;
@synthesize settingsButton;
@synthesize dayCardController;

- (id)init
{
    self = [super initWithNibName:@"KDDayListController" bundle:nil];
    if (self) {
        [self initNavigationBar];
    }
    return self;
}

- (void)dealloc
{
    [dayArray release];
    [dayListTable release];
    [aboutButton release];
    [settingsButton release];
    [dayCardController release];
    
    [super dealloc];
}

#pragma mark - UIViewController methods

- (void)viewDidLoad
{
    [super viewDidLoad];
        
    [self.dayListTable setSectionHeaderHeight:0.0f];
    [self.dayListTable setSectionFooterHeight:0.0f];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self bindDayList];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - IBAction methods

- (IBAction)showAbout:(id)sender
{
    KDAboutController *about =
        [[[KDAboutController alloc] init] autorelease];
    
    [self presentViewController:about
                       animated:YES
                     completion:nil];
}

- (IBAction)showSettings:(id)sender
{
    KDSettingsController *settings =
        [[[KDSettingsController alloc] init] autorelease];
    
    [self presentViewController:settings
                       animated:YES
                     completion:nil];
}

#pragma mark - UITableViewDelegate methods

-       (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:self.dayListTable])
    {
        KDDayController *dayController =
        [[[KDDayController alloc] init] autorelease];
        
        NSUInteger row = indexPath.row;
        if (indexPath.section > 0)
            row++;
        
        dayController.day = (NSDay *)[self.dayArray objectAtIndex:row];
        
        [self.navigationController pushViewController:dayController
                                             animated:YES];
    }
}

-       (CGFloat)tableView:(UITableView *)tableView
  heightForHeaderInSection:(NSInteger)section
{
    return 10.0f;
}

-       (CGFloat)tableView:(UITableView *)tableView
  heightForFooterInSection:(NSInteger)section
{
    return 0.0f;
}

-       (CGFloat)tableView:(UITableView *)tableView
   heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
        return 200.0f;
    else
        return [self.dayListTable rowHeight];
}

#pragma mark - UITableViewDataSource methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.dayArray == nil ||
        self.dayArray.count == 0)
        return 0;
    
    if (self.dayArray.count == 1)
        return 1;
    else
        return 2;
}

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section;
{
    if (section == 0)
        return 1;
    else
        return (self.dayArray.count - 1);
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger row = indexPath.row;
    if (indexPath.section > 0)
        row++;

    static NSString *TopCellIdentifier = @"CellIdentifier";
    static NSString *CellIdentifier = @"CellIdentifier";
    
    NSDay *day = [self.dayArray objectAtIndex:row];
    
    if (indexPath.section == 0) {
        
        KDTopDayTableViewCell *topCell =
            [tableView dequeueReusableCellWithIdentifier:TopCellIdentifier];
        
        if (topCell == nil) {
            topCell = [[[KDTopDayTableViewCell alloc]
                        initWithStyle:UITableViewCellStyleDefault
                        reuseIdentifier:CellIdentifier]
                       autorelease];
        }
        
        [topCell bindDay:day];
        
        return topCell;

    } else {
        
        KDDayTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        
        if (cell == nil) {
            cell = [[[KDDayTableViewCell alloc]
                    initWithStyle:UITableViewCellStyleDefault
                     reuseIdentifier:CellIdentifier] autorelease];
        }
        
        cell.delegate = self;

        [cell bindDay:day];
        
        return cell;
    }
}

#pragma mark - KDDayTableViewCellDelegate

-     (void)tableViewCell:(KDDayTableViewCell *)tableViewCell
 imageButtonTappedWithDay:(NSDay *)day
{
    [self showDayCard:day];
}

#pragma mark - Private methods

- (void)initNavigationBar
{
    UIBarButtonItem *addButton = [[UIBarButtonItem alloc]
                                  initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                                  target:self
                                  action:@selector(addNewDay)];
        
    self.navigationItem.rightBarButtonItem = addButton;
    
    [addButton release];
    
    UIBarButtonItem *tempBackButton = [[UIBarButtonItem alloc] init];
    tempBackButton.title = NSLocalizedString(@"Back", nil);
    
    self.navigationItem.backBarButtonItem = tempBackButton;
    
    [tempBackButton release];
        
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
    [dateFormat setDateFormat:NSLocalizedString(@"Short Date Format", nil)];
    
    self.title = [dateFormat stringFromDate:[NSDate date]];
    
    [dateFormat release];
}

- (void)addNewDay
{
    KDNewDayController *newDay = [[[KDNewDayController alloc] init]
                                  autorelease];
    
    [self.navigationController pushViewController:newDay
                                         animated:YES];
}

- (void)showDayCard:(NSDay *)day
{
    KDDayCardController *theDayCardController =
        [[[KDDayCardController alloc] init] autorelease];
    
    theDayCardController.day = day;
    theDayCardController.view.frame = [[UIScreen mainScreen] applicationFrame];
    theDayCardController.view.alpha = 0.0;
    
    self.dayCardController = theDayCardController;
    
    UIWindow *thisWindow = [[UIApplication sharedApplication] keyWindow];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3f];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    
    [thisWindow addSubview:self.dayCardController.view];
    self.dayCardController.view.alpha = 1.0;
    
    [UIView commitAnimations];
}

- (void)bindDayList
{
    KDAppDelegate *delegate = [KDAppDelegate sharedAppDelegate];
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"KDDay"
                                   inManagedObjectContext:delegate.managedObjectContext];
    
    [fetchRequest setEntity:entity];
    
    NSError *error = nil;
    
    NSArray *fetchResult = [delegate.managedObjectContext
                            executeFetchRequest:fetchRequest
                            error:&error];

    if (fetchResult == nil || fetchResult.count == 0) {
        self.dayArray = nil;
        [fetchRequest release];
        return;
    }
    
    self.dayArray = fetchResult;
    [fetchRequest release];
    
    [self.dayListTable reloadData];
}

@end
